<?php

namespace App\Http\Controllers;

use App\Http\Requests\ContactRequest;
use Illuminate\Http\Request;
use App\Contact;

class ContactController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(Request $req){
        $page = $req->has("page")? $req->page : 1;

        $per_page = $req->has("per_page")? $req->per_page : 10;
        $s_name =  $req->has("s_name")? $req->s_name : '';
        $q = "?page=$page&per_page=$per_page&s_name=$s_name";
        $req->session()->put("query_str",$q);

        $result = Contact::where('name','like',"%$s_name%")->paginate($per_page);
        if($page>$result->lastPage()){
           $page = $result->lastPage();
           $q = "?page=$page&per_page=$per_page&s_name=$s_name";
           return redirect("/contacts$q");
        }
        return view("contact-list")
            ->with("contacts",$result)
            ->with('s_name',$s_name)
            ;
    }

    public function view(Request $req, $id){
        $contact = Contact::find($id+0);
        if($contact)
            return view("view-contact")->with("contact",$contact);
        else
            return "记录不存在！"; //或者返回一个视图。
    }
    public function modify(Request $req, $id){
        $contact = Contact::find($id+0);
        if($contact)
            return view("edit-contact")->with("contact",$contact);
        else
            return "记录不存在！"; //或者返回一个视图。
    }
    public function delete(Request $req, $id){
        $res = Contact::destroy($id+0);
        if($res){
            $q = $req->session()->get('query_str','');
            return redirect("/contacts$q");
        }
        else{
            return "删除错误"; //或者返回一个视图。
        }
    }

    public function modify_save(ContactRequest $req, $id){
        $c = Contact::find($id+0);
        if(!$c){
            return "找不到要修改的记录"; // 或者返回视图
        }
        $c->name = $req->get("name",$c->name);
        $c->gender = $req->get("gender",$c->gender);
        $c->birth_date = $req->get("birth_date",$c->birth_date);
        $c->mobile_phone = $req->get("mobile_phone",$c->mobile_phone);
        $c->email = $req->get("email",$c->email);
        if($c->save()){
            return redirect("/contacts".$req->session()->get('query_str',''));
        }
        return "保存记录出错！";
    }

    public function saveNew(ContactRequest $req){
        $res = Contact::create($req->only(["name","gender","birth_date","mobile_phone","email"]));
        if($res){
            return redirect("/contacts".$req->session()->get('query_str',''));
        }
        return "保存记录出错！";
    }

    public function newContactForm(){
        return view('new-contact');
    }

}
